package com.demo.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class Hutool {

    /**
     * 以post方式发送请求, 解析JSONObject
     * @param url 目标地址
     * @param jsonObject 参数
     */
    public static void JsonObjectByPost(String url, JSONObject jsonObject) {
        HttpResponse response = HttpRequest
                .post(url)
                .charset("UTF-8")
                .header("Content-Type", "application/json")
                .body(jsonObject.toString())
                .execute();
        System.out.println("status code" + response.getStatus());
        System.out.println("enconding" + response.contentEncoding());
        System.out.println("body"+ response.body());
        System.out.println("content-type" + response.header("Content-Type"));
    }

    /**
     * 以get方式获取请求，解析JSONObject
     * @param url
     */
    public static void JsonObjectByGet(String url) {
        String res = HttpUtil.get(url);
        JSONObject jsonObject = new JSONObject(res);
        System.out.println(jsonObject.getInt("id"));
        System.out.println(jsonObject.getStr("name"));
    }


    public static void test() {
        String res = HttpUtil.get("http://localhost:8080/c");
        JSONArray objects = JSONUtil.parseArray(res);
        System.out.println(objects.get(0));
    }

}
